import React, { Component } from "react";
import { connect } from "react-redux";

import { addAction, minusAction, loadAction } from "./store/actionCreators";

// 将仓库的数据映射到组件的props里面
const mapStateToProps = (state) => {
  return {
    // 将仓库的count变成组件的props的count
    count: state.count,
    name: state.name,
    list: state.list,
  };
};

// 将仓库的reducer的方法映射到组件的props里面
const mapDispatchToProps = (dispatch) => {
  return {
    add(n) {
      dispatch(addAction(n));
    },
    minus() {
      dispatch(minusAction());
    },
    load() {
      dispatch(loadAction());
    },
  };
};

class App extends Component {
  render() {
    return (
      <>
        <h2>redux异步</h2>
        <button onClick={() => this.props.minus()}>-</button>
        <span>{this.props.count}</span>
        <button onClick={() => this.props.add(2)}>+</button>

        <hr />

        <ul>
          {this.props.list.map((item) => (
            <li key={item._id}>{item.title}</li>
          ))}
        </ul>
      </>
    );
  }

  componentDidMount() {
    this.props.load();
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
